﻿using System;
using System.Collections.Generic;
using DTC.Models;
using System.Threading;
using System.Linq;


namespace Common
{
    public enum CELL_MODE { NORMAL = 0, STOPING };
    public class ProductMachine
    {
        Queue<Product> Products = new Queue<Product>();
        List<TestSpan> spans = new List<TestSpan>();
        protected List<Test_Data> TestDatasToSave = new List<Test_Data>();
        public CELL_MODE cellMode = CELL_MODE.NORMAL;
        public Action<string> ShowMsg;
        public Action<List<TestSpan>> ShowTestSpan;
        public static object objLock = new object();
        public FIO01 m_IO { get; set; }
        public IOState state { get; set; }
        public string ModelName { get; set; }
        public object loker = new object();
   //     private ManualResetEvent finish = new ManualResetEvent(false);
        static int iStoppingIO = int.Parse(System.Configuration.ConfigurationManager.AppSettings["IOStopping"]);
        #region 属性：TestItems 测试项目列表
        List<TestItem> _testItems = new List<TestItem>();
        public List<TestItem> TestItems
        {
            get { return Product.ParseTestItems(className + ".xml"); }
        }
        #endregion
        #region 属性：className 所需要创建的产品类名
        public string className { get; set; }
        #endregion
        #region 属性：ProductCount测试的总量
        int productCount;//测试的总量
        public int totalFail { get; set; }
        public int ProductCount
        {
            get { return productCount; }
        }

        public ProductMachine(string ClassName)
        {
            className = ClassName;
        }
        #endregion
        public int PassCount { get; set; }
        #region 步进测试容器中的所有产品
        private void SaveTestDataToList(Test_Data  td)
        {
            TestDatasToSave.Add(td);
        }
        public void Step()
        {
            lock (loker)
            {
                spans.Clear();
                TestDatasToSave.Clear();
                if (cellMode == CELL_MODE.NORMAL)
                {
                    Product pd = ProductFactory.CreateProduct(className);
                    pd.m_IO = m_IO;
                    pd.ModelName = ModelName;
                    pd.ShowMsg = ShowMessage;
                    pd.ShowTestSpan = _ShowTestSpan;
                    pd.SaveTestDataToList = SaveTestDataToList;
                    Products.Enqueue(pd);
                }
                if ((++productCount) > TestItems.Count)
                {
                    if (Products.Count >= 1)
                    {
                        Product pd = Products.Dequeue();
                        if (pd.B_Fail)
                        {
                            CountManager.TotalFailCount++;
                            ShowMsg("[总体结果]失败");
                        }
                        else
                        {
                            CountManager.TotalPassCount++;
                            ShowMsg("[总体结果]成功");
                        }
                    }
                    else
                    {
                        ShowMsg("[错误]：[没有可用对象]");
                    }
                }
            //    int iStart = Environment.TickCount;
                System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                sw.Start();
                foreach (Product pd in Products)
                {
                    TestProduct(pd);
                }
                m_IO.State = new IOState(0x03);
                sw.Stop();
                LogHelper.WriteLog(typeof(Product), string.Format("数据采集完成,总用时[{0}]ms,写入IO 0x03", sw.ElapsedMilliseconds));
                spans.Reverse();
                ShowTestSpan(spans);
                if (m_IO.State[iStoppingIO])
                {
                    ShowMessage(string.Format("[停止模式],停止IO{0}", iStoppingIO.ToString()));
                    cellMode = CELL_MODE.STOPING;
                }
                else
                {
                    ShowMessage(string.Format("[正常模式],停止IO{0}", iStoppingIO.ToString()));
                    cellMode = CELL_MODE.NORMAL;
                }
                sw.Reset();
                sw.Start();
                ThreadPool.QueueUserWorkItem(SaveStepDataToDatabase, TestDatasToSave);
                sw.Stop();
                LogHelper.WriteLog(typeof(Product), string.Format("数据写入完成,总用时[{0}]ms", sw.ElapsedMilliseconds));
            }
        }
        private void SaveStepDataToDatabase(object dts)
        {
            try
            {
                List<Test_Data> TestDatas = CommonHelper.Clone<List<Test_Data>>((List<Test_Data>)dts);
                DTC.BLL.Test_DatasManager.InsertTestDatas(TestDatas);
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(typeof(ProductMachine), ex);
               // throw;
            }
        }
       
        private void TestProduct(object _pd)
        {
            lock (objLock)
            {
                Product pd = _pd as Product;
                if (pd.Test() < 0)
                {
                    totalFail++;
                }
                pd.StepLocation(); 
            }
        }
        #endregion
        public void _ShowTestSpan(List<TestSpan> testspans)
        {
            spans.AddRange(testspans);
        }

        public void ClearProducts()
        {
            Products.Clear();
            productCount = 0;
        }
        void ShowMessage(string Msg)
        {
          //  if (ShowMsg == null)
            {
                LogHelper.WriteLog(typeof(ProductMachine), Msg);
            }            
        }
    }

}
